package com.zkx.laolaiyi.service.impl;

import com.zkx.laolaiyi.constant.ExceptionMsgConstant;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 由于将admin和user拆开成两个表，需要自定义AuthenticationProvider，供AuthenticationManager使用
 */
@RequiredArgsConstructor
@Slf4j
@Component
public class AuthenticationProviderImpl implements AuthenticationProvider {
    private final UserDetailsServiceImpl userDetailsService;
    private final PasswordEncoder passwordEncoder;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = authentication.getPrincipal().toString();
//        String role = (String) authentication.getDetails();
        String role = ((AuthenticationTokenImpl) authentication).getRole();
        log.info("当前身份为：{}", role);
        UserDetails userDetails = userDetailsService.loadUserByUsernameAndRole(username, role);
        if (passwordEncoder.matches(password, userDetails.getPassword())) {
            throw new BadCredentialsException(ExceptionMsgConstant.IDENTITY_VALIDATE_EXCEPTION);
        }
        return new UsernamePasswordAuthenticationToken(userDetails, password);
    }

    @Override
    public boolean supports(Class<?> authentication) {
//        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
        return AuthenticationTokenImpl.class.isAssignableFrom(authentication);
    }
}
